package al19removeNthFromEnd;

import java.util.List;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class RemoveNthFromEnd19 {


    public static ListNode removeNthFromEnd(ListNode head, int n) {

        if (head.next == null){
            return null;
        }
        ListNode left = head;
        ListNode right = head;
        while (n>0 && right!=null){
            right= right.next;
            n--;
        }
        if (right==null){
            return head.next;
        }

        while (right.next!=null){
            left =left.next;
            right = right.next;
        }

        left.next = left.next.next;
        return head;
    }
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    // 主方法用于测试
    public static void main(String[] args) {
        // 创建两个有序链表
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
/*        l1.next.next = new ListNode(3);
        l1.next.next.next = new ListNode(4);
        l1.next.next.next.next = new ListNode(5);*/


        // 打印原链表
        System.out.println("List 1:");
        printList(l1);


        // 合并两个链表
        ListNode mergedList = removeNthFromEnd(l1, 2);

        // 打印合并后的链表
        System.out.println("Merged List:");
        printList(mergedList);
    }
}
